<?php
/**
 * Created by PhpStorm.
 * Script Name: Tpzs.php
 * Create: 2022/4/18 10:38
 * Description: 推品助手处理器
 * Author: fudaoji<fdj@kuryun.cn>
 */

namespace app\bot\controller;

use app\common\model\hanzi\Config;
use ky\Logger;

class Hanzi extends Addon
{
    private $switch;
    private $toWxid = '';
    /**
     * @var Config
     */
    private $configM;

    public function init($options = [])
    {
        parent::init($options); // TODO: Change the autogenerated stub
        $this->configM = new Config();
        $this->switch = $this->configM->getOneByMap([
            'bot_id' => $this->bot['id'], 'key' => 'switch', 'value' => 1
        ]);
        return $this;
    }

    /**
     * 机器人主动事件
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function deviceCallbackHandle(){
        $this->groupChatHandle();
    }

    /**
     * 群聊处理器
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function groupChatHandle(){
        if(empty($this->switch) || strpos($this->switch['wxids'], $this->groupWxid) === false){
            return false;
        }
        $this->toWxid = $this->groupWxid;
        //一、关键词
        $this->keyword();
    }

    /**
     * 私聊处理器
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function privateChatHandle(){
        if(empty($this->switch) || strpos($this->switch['wxids'], $this->fromWxid) === false){
            return false;
        }
        $this->toWxid = $this->fromWxid;
        //一、关键词
        $this->keyword();
    }

    /**
     * 关键词回复
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    private function keyword(){
        $msg = trim($this->content['msg']);
        $arr = explode("的笔顺", $msg);
        if(strpos($msg, "的笔顺") !== false && $this->fromWxid != $this->botWxid && strpos($msg, "\r\r") === false && empty($arr[1])){
            $text = trim($arr[0]);
            $reply = '点击链接查看【'.$text . '】的笔画笔顺：' . request()->domain() . url('wap/hanzi/index', ['text' => $text]);
            $this->botClient->sendTextToFriends(['robot_wxid' => $this->content['robot_wxid'], 'to_wxid' => $this->toWxid, 'msg' => $reply]);
        }
    }
}